import { ModalForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { Button, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { createDingRobot } from '../../service';
import type { CreateDingRobotType } from '../../typings.d';
import { useModel } from 'umi';
import { Role } from '@/utils/typings.d';
import { queryCompanies } from '@/pages/SystemUser/service';

const CreateDingRobot = (props: { reload: () => void }) => {
  const { initialState } = useModel('@@initialState');
  const userRole = initialState?.currentUser?.role;
  // const [form] = ProForm.useForm();
  return (
    <ModalForm<CreateDingRobotType>
      width={650}
      title="创建钉钉机器人"
      layout="horizontal"
      labelCol={{ span: 6 }}
      // form={form}
      wrapperCol={{ span: 16 }}
      modalProps={{
        destroyOnClose: true,
      }}
      trigger={
        <Button type="primary">
          <PlusOutlined /> 新建钉钉机器人
        </Button>
      }
      onFinish={async (values) => {
        const res = await createDingRobot(values);
        if (res?.success) {
          message.success({ content: res.message, key: 'create_ding' });
          props?.reload();
          // form.resetFields();
          return true;
        }
        message.error({ content: res?.message, key: 'create_ding' });
        return false;
      }}
    >
      <ProFormText
        width="xl"
        name="name"
        label="机器人名"
        tooltip="最长为 12 位"
        placeholder="请输入钉钉机器人名称"
        rules={[
          {
            required: true,
            validator: async (_, nameVal) => {
              if (nameVal.length < 2 || nameVal.length > 12)
                return Promise.reject(new Error('钉钉名长度应满足不少于2个字符，不超过12个字符'));
              return Promise.resolve(nameVal);
            },
          },
        ]}
      />
      <ProFormTextArea
        width="xl"
        name="webhook"
        label="Webhook"
        placeholder="请输入webhook链接"
        required
      />
      <ProFormTextArea
        width="xl"
        name="secret"
        label="Secret"
        placeholder="请输入secret"
        required
      />
      <ProFormTextArea
        width="xl"
        name="description"
        label="相关描述"
        placeholder="请输入钉钉机器人描述"
      />
      {userRole === Role.ADMIN && (
        <ProFormSelect
          name="ownerId"
          label="用户归属公司"
          showSearch
          debounceTime={200}
          rules={[{ required: true, message: '请选择用户目标公司' }]}
          placeholder="请选择用户归属公司(如未找到目标公司，请优先创建[企业管理者])"
          request={(val) => queryCompanies(val.keyWords, true)}
        />
      )}
    </ModalForm>
  );
};

export default CreateDingRobot;
